﻿using Avalon.Core.Data;
using Avalon.Core.MVC.Attributes;
using Avalon.Core.Providers;
using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Avalon.Core.MVC.Helpers
{
    public class CreateFormHelper : Avalon.Core.MVC.IViewRenderHelper
    {
        public MvcHtmlString Render(HtmlHelper htmlHelper)
        {
            ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => htmlHelper.ViewData.Model, htmlHelper.ViewData.Model.GetType());
            if (modelMetadata.Model == null) modelMetadata.Model = htmlHelper.ViewContext.ViewData.Model;

            string controllerName = ControllerProvider.GetControllerName(modelMetadata.ModelType);
            string actionName = htmlHelper.ViewContext.RouteData.Values["action"].ToString();

            StringBuilder builder = new StringBuilder();

            builder.AppendFormat(@"<form method='post' action='/{0}/{1}'>", controllerName, actionName);

            // When this form is used to create a referenced type set the parent information
            ModelMetadata parentMetadata = modelMetadata.GetParentProperty();
            if (parentMetadata != null) {
                string parentId = parentMetadata.GetParentId();
                builder.AppendFormat(@"<input type='hidden' name='parentId' value='{0}' />", parentId);
                builder.AppendFormat(@"<input type='hidden' name='parentName' value='{0}' />", parentMetadata.ModelType.Name);
            }

            builder.AppendFormat(@"<fieldset><legend>{0}</legend>", modelMetadata.GetTitle());

            foreach (var propertyMetadata in modelMetadata.Properties.Where(p => p.IsSimpleProperty()).OrderBy(p => p.Order))
            {
                if (propertyMetadata.AdditionalValues.ContainsKey(IgnoreAttribute.Key)) continue;
                else builder.AppendFormat(ControlBuilder.CreateInputControl(htmlHelper, propertyMetadata));
            }

            builder.AppendFormat(@"<input type='submit' class='btn' value='Save' />");

            if (modelMetadata.Properties.FirstOrDefault(p => p.AdditionalValues.ContainsKey(ParentAttribute.Key)) != null)
            {
                var property = modelMetadata.Properties.FirstOrDefault(p => p.AdditionalValues.ContainsKey(ParentAttribute.Key));
                var propertyValue = htmlHelper.ViewData.Model.GetType().GetProperty(property.PropertyName).GetValue(htmlHelper.ViewData.Model);
                if (propertyValue == null || ((Guid)propertyValue) == Guid.Empty) propertyValue = htmlHelper.ViewBag.parentId;
                builder.AppendFormat(@"<a href='/{0}/{1}/{2}' class='btn'>Cancel</a>", property.AdditionalValues[ParentAttribute.Key], "Detail", propertyValue);
            }
            else
            {
                var id = htmlHelper.ViewData.Model.GetType().GetProperty("Id").GetValue(htmlHelper.ViewData.Model);
                builder.AppendFormat(@"<a href='/{0}/{1}/{2}' class='btn'>Cancel</a>", controllerName, "Detail", id != null ? id.ToString() : string.Empty);
            }

            builder.AppendFormat(@"</fieldset>");
            builder.AppendFormat(@"</form>");

            return new MvcHtmlString(builder.ToString());
        }


    }
}
